/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.send;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lxk.event.helper.EventHelper;
import com.lxk.event.oms.OrderOptionLogEvent;
import com.lxk.event.oms.enums.OrderEnums;
import com.lxk.oms.order.domain.req.SendOrderReq;
import com.lxk.oms.order.domain.vo.OmsOrderVo;
import com.lxk.oms.order.service.IOmsOrderService;
import com.lxk.service.core.Result;
import com.lxk.service.ums.api.UmsServiceApi;
import com.lxk.service.ums.response.UmsUserDto;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.log.LFLog;
import com.yomahub.liteflow.log.LFLoggerManager;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ValidationUtils;

import static com.lxk.oms.flow.send.FlowSendOrderNodeConst.FILL_CONTEXT_SEND_ORDER_NODE;

/**
 * 订单发货/配送
 *
 * @author heyi
 * 2024/9/3
 */
@AllArgsConstructor
@LiteflowComponent(FILL_CONTEXT_SEND_ORDER_NODE)
public class OrderFillSendOrderContextNode extends NodeComponent {
    private final LFLog log = LFLoggerManager.getLogger(FlowExecutor.class);
    private final IOmsOrderService omsOrderService;
    private final UmsServiceApi umsServiceApi;

    @Override
    public void beforeProcess() {
        SendOrderReq sendOrderReq = getRequestData();
        ValidationUtils.validate(sendOrderReq);
        SendOrderContext contextBean = getContextBean(SendOrderContext.class);
        contextBean.setOrderSn(sendOrderReq.getOrderNo());
        contextBean.setOrderType(sendOrderReq.getOrderType());
        contextBean.setOptionUserId(sendOrderReq.getOptionUserId());
        contextBean.setOptionUserType(sendOrderReq.getOptionUserType());
        contextBean.setTenantId(sendOrderReq.getTenantId());
        contextBean.setDeliveryName(sendOrderReq.getDeliveryName());
        contextBean.setDeliverySn(sendOrderReq.getDeliverySn());
        contextBean.setShipperCode(sendOrderReq.getShipperCode());
        contextBean.setSendOptionEvent(sendOrderReq.getSendOptionEvent());
    }

    @Override
    public void process() throws Exception {
        SendOrderReq sendOrderReq = getRequestData();
        OmsOrderVo order = omsOrderService.queryByOrderSn(sendOrderReq.getOrderNo());
        if (ObjectUtil.isNull(order)) {
            String msg = StrUtil.format("发货时,订单不存在,{}", sendOrderReq.getOrderNo());
            log.error(msg);
            throw new ServiceException(msg);
        }

        Integer orderStatus = order.getStatus();
        if (ObjectUtil.notEqual(orderStatus, OrderEnums.OrderStatus.SEND_300.getCode())) {
            String msg = StrUtil.format("发货时,订单{}尚未处于待发货状态,当前状态{}", order.getOrderNo(), OrderEnums.OrderStatus.getByCode(orderStatus).getName());
            log.error(msg);
            throw new ServiceException(msg);
        }
        SendOrderContext contextBean = getContextBean(SendOrderContext.class);
        contextBean.setOmsOrderVo(order);
        contextBean.setMerId(order.getMerId());
        contextBean.setOrderType(OrderEnums.OrderType.getByCode(order.getOrderType()));
        contextBean.setDeliveryType(OrderEnums.DeliveryType.getByCode(order.getDeliveryType()));
        Result<UmsUserDto> umsUserDtoResult = umsServiceApi.queryById(order.getUserId());
        if (umsUserDtoResult.isFail()) {
            throw new ServiceException(umsUserDtoResult.getMsg());
        }
        contextBean.setUser(umsUserDtoResult.getData());
    }

    @Override
    public void onError(Exception e) throws Exception {
        OrderOptionLogEvent orderCreateEvent = new OrderOptionLogEvent();
        SendOrderContext contextBean = getContextBean(SendOrderContext.class);
        OmsOrderVo omsOrder = contextBean.getOmsOrderVo();
        if (ObjectUtil.isNotNull(omsOrder)) {
            orderCreateEvent.setOrderSn(omsOrder.getOrderNo());
            orderCreateEvent.setTenantId(contextBean.getTenantId());
            orderCreateEvent.setOptionUserId(contextBean.getOptionUserId());
            orderCreateEvent.setOptionUserType(contextBean.getOptionUserType());
            orderCreateEvent.setOrderLogEnums(OrderOptionLogEvent.OrderLogEnums.ORDER);
            orderCreateEvent.setErrorMsg(e.getMessage());
            orderCreateEvent.setContent(e.getMessage());
            EventHelper.publishEvent(orderCreateEvent);
        }
    }
}
